package com.cskaoyan.config;

import com.cskaoyan.bean.model.MarketUser;
import com.cskaoyan.bean.model.MarketUserExample;
import com.cskaoyan.mapper.MarketUserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    MarketUserMapper userMapper;

    // 使用subject.login(token)登录的时候，传入的token，根据用户名查询当前系统内的用户信息
    // 构造为认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        MarketUserExample example = new MarketUserExample();
        example.createCriteria().andUsernameEqualTo(username).andDeletedEqualTo(false);
        List<MarketUser> marketUsers = userMapper.selectByExample(example);
        if (marketUsers == null || marketUsers.size() == 0) {
            return null;
        } else {
            MarketUser marketUser = marketUsers.get(0);
            // 1. 保存在Subject中的用户信息，在登录之后，可以随时获取的信息，可以保存用户id
            // 2. 用户在系统中的凭据(密码)
            // 3. realmName 没啥用
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(marketUser.getId(),marketUser.getPassword(),this.getName());
            return authenticationInfo;
        }
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

}
